//
//  FYEmoticonController.swift
//  dugeweibo
//
//  Created by pelesys on 16/8/10.
//  Copyright © 2016年 杜方宜. All rights reserved.
//

import UIKit

private let EmotionCell = "EmotionCell"
class FYEmoticonController: UIViewController {
   // MARK:-定义属性
    var emotionCallBack : (_ emotion : FYEmotion) ->()
    
   // MARK:-懒加载属性
    private lazy var collectionView : UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: EmotionCollectionViewLayout())
    private lazy var tooBar : UIToolbar = UIToolbar()
    private lazy var manager = FYEmoticonManager()
    // MARK:-自定义构造函数
   
    init (emotionCallBack : @escaping (_ emotion : FYEmotion) ->()){
        self.emotionCallBack = emotionCallBack
        super.init(nibName : nil,bundle:nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK:-系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }


}
// MARK:-设置UI界面内容
extension FYEmoticonController {
    private func setupUI(){
       //1.添加子控件
        view.addSubview(collectionView)
        view.addSubview(tooBar)
        collectionView.backgroundColor = UIColor.purple
        tooBar.backgroundColor = UIColor.darkGray
        //2.设置子控件的frame
        //想用autolayout，就将translatesAutoresizingMaskIntoConstraints设为NO
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        tooBar.translatesAutoresizingMaskIntoConstraints = false
        let views = ["tBar" : tooBar, "cView" : collectionView]
        var cons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[tBar]-0-|", options: [], metrics: nil, views: views)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[cView]-0-[tBar]-0-|", options: [.alignAllLeft,.alignAllRight], metrics: nil, views: views)
        view.addConstraints(cons)
        //3.准备collectionview
        prepareForCollectionView()
        
        //4.准备toolBar
        prepereForToolBar()
        
    }
    private func prepareForCollectionView(){
        collectionView.register(FYEmioticonViewCell.self, forCellWithReuseIdentifier: EmotionCell)
           collectionView.dataSource = self
           collectionView.delegate = self
    }
    private func prepereForToolBar(){
        // 1.定义toolBar中titles
        let titles = ["最近", "默认", "emoji", "浪小花"]
        
        // 2.遍历标题,创建item
        var index = 0
        var tempItems = [UIBarButtonItem]()
        for title in titles {
            let item = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(itemClick(item:)))
            item.tag = index
            index += 1
            
            tempItems.append(item)
            tempItems.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        
        // 3.设置toolBar的items数组
        tempItems.removeLast()
        tooBar.items = tempItems
        tooBar.tintColor = UIColor.orange

        
    }
    @objc private func itemClick(item : UIBarButtonItem){
        // 1.获取点击的item的tag
        let tag = item.tag
        
        // 2.根据tag获取到当前组
        let indexPath = NSIndexPath(item: 0, section: tag)
        
        // 3.滚动到对应的位置
        collectionView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: true)

    }
}
// MARK:-collectionView的数据源和代理方法
extension FYEmoticonController :UICollectionViewDelegate,UICollectionViewDataSource {
  
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return manager.packages.count
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let package = manager.packages[section]
        
        return package.emotions.count
        
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        //1.创建cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmotionCell, for: indexPath as IndexPath) as! FYEmioticonViewCell
        //2.给cell设置数据
        let package = manager.packages[indexPath.section]
        let emotion = package.emotions[indexPath.item]
        cell.emotion = emotion
        
        
        return cell
        
    }
    //代理方法
    private func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //1.取出点击的表情
        let package = manager.packages[indexPath.section]
        let emotion = package.emotions[indexPath.item]
        //2.将点击的表情插入最近分组中
        insertRecentlyEmoticon(emoticon: emotion)
        //3.将表情回调给外界控制器
        emotionCallBack(emotion)
        
    }
    
    private func insertRecentlyEmoticon(emoticon : FYEmotion){
        //1.如果是空白表情或者删除按钮 ,不需要插入
        if emoticon.isRemove || emoticon.isEmpty {
            return
        }
        //2.删除一个表情
        if manager.packages.first!.emotions.contains(emoticon) {//原来该有表情
            let index = ( manager.packages.first?.emotions.firstIndex(of: emoticon))!
            manager.packages.first?.emotions.remove(at: index)
            
        }else{//原来没有这个表情
            manager.packages.first?.emotions.remove(at: 19)
            
        }
        //3.将emotion插入最近分组中
        manager.packages.first?.emotions.insert(emoticon, at: 0)
        
    }
}
class EmotionCollectionViewLayout: UICollectionViewFlowLayout {
    override func prepare() {
        //1.计算itemWH
        let itemWH = UIScreen.main.bounds.width / 7
        //2.设置layout的属性
        itemSize = CGSize.init(width: itemWH, height: itemWH)
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = .horizontal
        //3.设置collectionview属性 UICollectionViewLayout的属性
        collectionView?.isPagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
        let insetMargin = ((collectionView?.bounds.height)! - 3 * itemWH) / 2
        collectionView?.contentInset = UIEdgeInsets(top: insetMargin, left: 0, bottom: insetMargin, right: 0)
        
    }
}
